import { Component } from '@angular/core';
import {NavController, ModalController, AlertController, ToastController} from 'ionic-angular';
import {SignOrlogin} from '../sign-orlogin/sign-orlogin'
import {UserInfoPage} from "../user-info/user-info";
import {ScanPage} from "../scan/scan";
import {VersionsPage} from "../versions/versions";
import { StorageService } from "../../providers/StorageService";
import {UserInfo} from "../../model/UserInfo";

import {USERFACE_PATH} from "../../providers/Constants"

import { BaseUI } from '../../common/baseui';
import {MySportsPage} from "../my-sports/my-sports";
import {SportService} from "../../providers/SportService";
import {JmessageChenyu} from "jmessage-chenyu";

import {FileTransferObject} from "@ionic-native/file-transfer";
import {FileTransfer} from "@ionic-native/file-transfer";
import {File} from "@ionic-native/file";
import {HttpService} from "../../providers/HttpService";
import {FILE_SERVER} from "../../providers/Constants";
import { AppVersion } from '@ionic-native/app-version';

// import { FileOpener } from '@ionic-native/file-opener';

@Component({
  selector: 'page-usercenter',
  templateUrl: 'usercenter.html'
})
export class UsercenterPage extends BaseUI{
	  params: Object;
  	pushPage: any;
    islogin: boolean;
    userInfo:UserInfo;
    userFaceImg:any;
    sportList:any;
    version:string;
    serverVersion:string;
    // status:boolean =false;
  constructor(
  	public navCtrl: NavController,
  	public modalCtrl: ModalController,
    private storageService: StorageService,
    public alertCtrl:AlertController,
    public toastCtrl: ToastController,
    public  sportService:SportService,
    public jmessageChenyu:JmessageChenyu,
    public transfer:FileTransfer,
    public file:File,
    // public fileOpener:FileOpener
    public httpService:HttpService,
    private appVersion: AppVersion,
  	) {

    super();

  }
  //打开注册/登陆
  openSignupOrlogin(){
  	let myModal = this.modalCtrl.create(SignOrlogin);
   	myModal.present();
  }

  //用户注销
  // logout() {
  //   this.storageService.remove('UserInfo');
  //  this.checkLogin();
  // }

  ionViewDidEnter() {
    console.log("进入个人中心页面");
    this.checkLogin();//加载页面前检查用户是否登录
  }

  //检查是否登录
  checkLogin(){
    if (this.storageService.read<UserInfo>('UserInfo')!=null) {
      console.log(this.storageService.read<UserInfo>('UserInfo'));
      this.userInfo = this.storageService.read<UserInfo>('UserInfo');
      console.log(this.userInfo.phone);
      this.userFaceImg = USERFACE_PATH+"/"+this.userInfo.userFace;
      this.islogin=true;//修改
    }else{
      this.islogin=false;
    }
  }

  /**
   * 跳转到扫描二维码的页面，加上 animate = false 的参数是为了
   * 相机能够在整个屏幕中显示，如果不加，相机就出不来。
   * animate 的参数默认值为 true
   *
   * @memberof MorePage
   */
  gotoScanQRCode() {
    this.navCtrl.push(ScanPage, null, { "animate": false });
  }

  gotoUserInfoPage() {
    this.navCtrl.push(UserInfoPage);
  }

  gotoVersions() {
    this.navCtrl.push(VersionsPage);
  }
  //清除缓存
  clearCache(){
    let confirm = this.alertCtrl.create({
      message: '确认要清除缓存?',
      buttons: [
        {
          text: '取消',
          handler: () => {
            // console.log('Disagree clicked');
          }
        },
        {
          text: '确定',
          handler: () => {
            localStorage.removeItem('firstIn');
            super.showToast(this.toastCtrl, "缓存清除成功。",'bottom');
          }
        }
      ]
    });
    confirm.present();
  }

  //我发布的活动
  pubSportFromMyself(){
    this.sportService.selectListByUserId(this.userInfo.id).subscribe(res => {
      this.navCtrl.push(MySportsPage,{title:'我发布的活动',sportList:res['data']});
    })
  }
  //我参加的活动
  slectIJoinSports(){
    this.sportService.selectIJoinSports(this.userInfo.id).subscribe(res => {
      this.navCtrl.push(MySportsPage,{title:'我参加的活动',sportList:res['data']});
    })
  }

  //我发布的动态
  opneMySportDynamic(){
    this.navCtrl.push('MySportDynamicPage');
  }

  //最近联系人
  openCatactPerson(){
    this.navCtrl.push("MycontactpersonsPage",{userId:this.userInfo.id});
  }

  downloadApp(apkUrl) {
    let alert = this.alertCtrl.create({
      title: '下载进度：0%',
      enableBackdropDismiss: false,
      buttons: ['后台下载']
    });
    alert.present();

    const fileTransfer: FileTransferObject = this.transfer.create();
    const apk = this.file.externalRootDirectory + '易校园.apk'; //apk保存的目录
    fileTransfer.download(apkUrl, apk).then(() => {
      // this.fileOpener.open(apk, 'application/vnd.android.package-archive').then(() =>{
      //   console.log('File is opened')
      // }).catch(e => {
      //   console.log('Error openening file', e)
      // });
    });
    fileTransfer.onProgress((event: ProgressEvent) => {
      let num = Math.floor(event.loaded / event.total * 100);
      if (num === 100) {
        alert.dismiss();
      } else {
        let title = document.getElementsByClassName('alert-title')[0];
        title && (title.innerHTML = '下载进度：' + num + '%');
      }
    });
  }

  update(){
    this.httpService.httpGet(FILE_SERVER+"/www/chcp.json").subscribe(res=>{
      this.serverVersion=res['version'];
      this.appVersion.getVersionNumber().then(v => {
        this.version =v;
        alert(this.version+":"+this.serverVersion);
        if(this.serverVersion>this.version){
          super.showAlert(this.alertCtrl,"升级提示",'当前已经为最新版本',"确定");
        }else {
          var apkUrl=FILE_SERVER+'/apk/yixiaoy.apk';
          this.alertCtrl.create({
            title: '升级提示',
            subTitle: '发现新版本,是否立即升级？',
            buttons: [{
              text: '取消'
            }, {
              text: '确定',
              handler: () => {
                this.downloadApp(apkUrl);
              }
            }]
          }).present();
        }
      });
    });

  }
  loveSport(){
    this.navCtrl.push("LovesportsPage");
  }

}
